import React, { useEffect, useState } from 'react'
import { Button, Upload } from 'antd'
import { UploadChangeParam, UploadFile } from 'antd/es/upload'
import axios from 'axios'

const Index: React.FC = () => {
  const [urls, setUrls] = useState<{ name: string, url: string }[]>([])
  const onChange = (info: UploadChangeParam<UploadFile<any>>) => {
    if (info.file.response) {
      const { data } = info.file.response
      console.log(data)
      setUrls(urls => {
        return [...urls, { name: data.name, url: data.url }]
      })
    }
  }
  const fetchUrlsList = async () => {
    const resp = await axios.get('/api/upload/ali/oss/list')
    setUrls(() => {
      return resp.data.data.objects.map((v: any) => {
        return {
          name: v.name,
          url: v.url
        }
      })

    })
  } 
  const handleDelete = (name: string) => {
    axios.delete('/api/upload/ali/oss/' + name).then(() => {
      fetchUrlsList()
    })
  }

  useEffect(() => {
    fetchUrlsList()
  }, [])
  return (
    <div>
      <Upload.Dragger multiple action="/api/upload/ali/oss" method='post' onChange={onChange} itemRender={() => ""}>
        <Button>上传</Button>
      </Upload.Dragger>
      <div style={{ display: 'flex', flexWrap: 'wrap' }}>
        {
          urls.map((v, i) => {
            return <div>
               <img title={v.name} src={v.url} key={i} style={{ margin: 10 }} height={100} alt="" onClick={() => handleDelete(v.name)}/>
              <div style={{ textAlign: 'center' }}>
              <a href={v.url}>下载</a>
              </div>
            </div>
          })
        }
      </div>
    </div>
  )
}

export default Index